/*
 * 版权所有：杭州领域向尚科技有限公司
 * 地址：浙江省杭州市滨江区滨安路688号天和高科技产业园5-2311
 *
 * (c) Copyright Hangzhou  Area Up Technology Co., Ltd.
 */

package com.treasure.mall.zbqmallmanager.base.security;

import com.treasure.mall.zbq.common.constant.Constant;
import com.treasure.mall.zbq.common.ienum.auth.RoleEnum;
import com.treasure.mall.zbq.common.ienum.base.CodeDescEnumHelper;
import com.treasure.mall.zbqmallmanager.base.exception.VerifyCodeException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author allan
 * @date 10/11/2017
 */
public class StAuthenticationProcessingFilter extends UsernamePasswordAuthenticationFilter {
    private static final String METHOD = "POST";

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!METHOD.equals(request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
//            String verifyCode = String.valueOf(request.getSession().getAttribute("verifyCode"));
//            String requestCode = request.getParameter("verifyCode");

//            //开发时就不校验验证码了
//            if (request.getSession().getAttribute(Constant.VERIFY_TAG) != null) {
//                if (StringUtils.isEmpty(verifyCode)
//                        || StringUtils.isEmpty(requestCode)
//                        || !verifyCode.equalsIgnoreCase(requestCode)) {
//                    throw new VerifyCodeException("验证码不正确");
//                }
//            }

            String username = request.getParameter(getUsernameParameter());
            String password = request.getParameter(getPasswordParameter());
            String role = request.getParameter("role");
            RoleEnum roleEnum = CodeDescEnumHelper.getEnumTypeByCode(RoleEnum.class, role);
            if (username == null) {
                username = "";
            }

            if (password == null) {
                password = "";
            }

            username = username.trim();
            UsernamePasswordAuthenticationToken authRequest = new StAuthenticationToken(username, password, roleEnum);
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }


}
